package com.baidu.bos.realm;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.baidu.bos.dao.IFunctionDao;
import com.baidu.bos.dao.IUserDao;
import com.baidu.bos.domain.Function;
import com.baidu.bos.domain.User;

public class BOSRealm extends AuthorizingRealm {
	@Resource
	private IUserDao userDao;
	@Resource
	private IFunctionDao functionDao;
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		String username = usernamePasswordToken.getUsername();
		//然后根据用户名去数据库查询密码,然后交给安全管理器验证
		User user = userDao.findByUsername(username);
		if (user == null) {
			//没有找到该用户
			return null;
		}
		//第一个参数可以传递任意对象,并且可以在以后任意的地方都可以取出
		//第二个参数为数据库查询出来的密码
		//第三个参数为当前ralm的类名
		SimpleAuthenticationInfo info = 
				new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
		return info;
	}
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//根据当前用户查询数据库,获得对应数据库权限信息
		User user = (User) principals.getPrimaryPrincipal();
		List<Function> list = null;
		if (user.getUsername().equals("admin")) {
			list = functionDao.findAll();
			info.addStringPermission("admin");
		}else {
			//从数据库查询当前用户对应的权限
			list = functionDao.findFunctionByUserid(user.getId());
		}
		for (Function function : list) {
			info.addStringPermission(function.getCode());
		}
		return info;
	}

}
